package cn.yeziji.forum.common;

import lombok.Data;

/**
 * 分页
 *
 * @author gzkemays
 * @since 2021/12/23 23:15
 */
@Data
public class Paging {
  /** 当前页码 */
  int page;
  /** 总页码 */
  int totalPage;
  /** 总数据量 */
  int total;
  /** 截取多少位 */
  int limit;

  public static PagingBuilder init() {
    return new PagingBuilder();
  }

  public static final class PagingBuilder {
    int page;
    int totalPage;
    int total;
    int limit;

    private PagingBuilder() {}

    public PagingBuilder page(int page) {
      this.page = page;
      return this;
    }

    public PagingBuilder totalPage(int totalPage) {
      this.totalPage = totalPage;
      return this;
    }

    public PagingBuilder total(int total) {
      this.total = total;
      return this;
    }

    public PagingBuilder limit(int limit) {
      this.limit = limit;
      return this;
    }

    public Paging build() {
      Paging paging = new Paging();
      paging.limit = this.limit;
      paging.total = this.total;
      paging.totalPage = this.totalPage;
      paging.page = this.page;
      return paging;
    }
  }

  public int currentPage() {
    return page == 0 ? 1 : page;
  }

  public int prefix() {
    if (page == 1 || page == 0) {
      page = 0;
    }
    return (page - 1) * limit;
  }

  public int last() {
    return limit;
  }

  public void total(int total) {
    this.total = total;
  }

  public int totalPage() {
    if (limit != 0) {
      double tp = (double) total / limit;
      int ceil = (int) Math.ceil(tp);
      return ceil == 0 ? 1 : ceil;
    } else {
      return total;
    }
  }
}
